<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/7/25 0025
 * Time: 17:07
 */

namespace framework\library;


class Response
{

    protected $contentType = "text/html";
    protected $charset = "utf-8";
    protected $code = 200;
    protected $header = [];
    protected $options = [];
    protected $data;
    protected $content;


    public function __construct($data = '', $code = 200, array $header = [])
    {
        $this->data = $data;

        $this->contentType($this->contentType, $this->charset);

        $this->code   = $code;
        $this->header = array_merge($this->header, $header);
    }

    // 创建默认相应或选择对应格式的相应模板
    public static function create($data = '', $type = '', $code = 200, array $header = [])
    {
        $class = false !== strpos($type, '\\') ? $type : '\\framework\library\response\\' . ucfirst(strtolower($type));

        if (class_exists($class)) {
            return new $class($data, $code, $header);
        }

        return new static($data, $code, $header);
    }

    // 发送响应到客户端
    public function send()
    {
        // 处理输出数据
        $data = $this->getContent();

        if (!headers_sent() && !empty($this->header)) {
            // 发送状态码
            http_response_code(200);
            // 发送头部信息
            foreach ($this->header as $name => $val) {
                header($name . (!is_null($val) ? ':' . $val : ''));
            }
        }

        // 输出数据到客户端
        echo $data;
    }

    public function contentType($contentType, $charset = 'utf-8')
    {
        $this->header['Content-Type'] = $contentType . '; charset=' . $charset;

        return $this;
    }

    // 获取格式化响应输出
    public function getContent()
    {
        if (null == $this->content) {
            $content = $this->output($this->data);

            $this->content = (string) $content;
        }

        return $this->content;
    }


}